package cc.c3p0.admin.utils;

import cc.c3p0.admin.common.constants.SystemConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * Jwt助手类
 * Created by binchao on 2017/5/11.
 */
public class JwtHelper {

    private static final Logger LOG = LoggerFactory.getLogger(JwtHelper.class);

    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception e) {
            LOG.error("解码失败：{}", e.getMessage());
        }
        return null;
    }

    public static String createJWT(String userId, String username, String gIds, long TTLMillis, String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        // 添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .signWith(signatureAlgorithm, signingKey)
//                .claim("role", role)
//                .claim("uniqueName", name)
                .claim(SystemConstants.CURRENT_USER_ID, userId)
                .claim("username", username)
                .claim("gIds", gIds);
//                .setIssuer(issuer)
//                .setAudience(audience);

        // 添加token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        return builder.compact();
    }

}
